<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              {{ project.projectName }}
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="项目编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              {{ project.projectCode }}
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="开标时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bidOpeningTime">
              <j-date
                placeholder="请选择开标时间"
                :showTime="true"
                v-model="model.bidOpeningTime"
                dateFormat="YYYY-MM-DD HH:mm:ss"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="选择标室" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                style="width: 180px"
                placeholder="请选择"
                v-model="model.biddingRoomId"
                dictCode="ex_bidding_room where 1 = 1,room_name,id"
                :disabled="true"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              label="开标室"
              :labelCol="labelCol2"
              :wrapperCol="wrapperCol2"
              prop="bidOpeningAddress"
            >
              <a-input  placeholder="开标室" v-model="model.bidOpeningAddress" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="24">
            <a-form-model-item label="关联标段" :labelCol="labelCol2" :wrapperCol="wrapperCol2">
              <j-checkbox v-model="model.exSectionIds" :options="exSectionOptions" style="line-height: 30px" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="4"> </a-col>
          <a-col :span="20">
            <a-radio-group v-model="selectRoomItem" @change="changeSelectRoomItem">
              <a-table :dataSource="dataSource" :columns="columns" :pagination="false">
                <!-- :scroll="{ y: 400 }" -->
                <span slot="action" slot-scope="text, index, record">
                  <template v-if="text.split('_')[2] == 'true'">
                    <a-tag color="green">已占用 </a-tag>
                  </template>
                  <template v-else>
                    <a-radio :value="text">空闲</a-radio>
                  </template>
                </span>
                <!-- <template slot="footer" slot-scope="currentPageData">
                  <a @click="next()">更多</a>
                </template> -->
              </a-table>
              <div
                v-if="showLoadingMore"
                :style="{ textAlign: 'center', marginTop: '12px', height: '32px', lineHeight: '32px' }"
              >
                <a-spin v-if="loadingMore" />
                <a-button v-else @click="next"> 加载更多 </a-button>
              </div>
            </a-radio-group>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import { httpAction, getAction } from '@/api/manage'
import { registerAnimation } from 'viser-vue'
import moment from 'moment'
import DeptBaseInfoVue from '../../system/modules/DeptBaseInfo.vue'
export default {
  name: 'ExZbidOpeningArrangeForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
  },
  data() {
    return {
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
      loadingMore: false,
      showLoadingMore: true,
      selectRoomItem: '',
      model: {},
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        bidOpeningTime: [{ required: true, message: '请输入开标时间!' }],
        bidOpeningAddress: [{ required: true, message: '请输入开标说明!' }],
      },
      refKeys: ['exZbidChangdiandbd'],
      tableKeys: ['exZbidChangdiandbd'],
      activeKey: 'exZbidChangdiandbd',
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      exSectionOptions: [],
      url: {
        add: '/exZbidOpeningArrange/exZbidOpeningArrange/add',
        edit: '/exZbidOpeningArrange/exZbidOpeningArrange/edit',
        queryById: '/exZbidOpeningArrange/exZbidOpeningArrange/queryById',
        exZbidChangdiandbd: {
          list: '/exZbidOpeningArrange/exZbidOpeningArrange/queryExZbidChangdiandbdByMainId',
        },
        records: {
          list: '/exZbidOpeningArrange/exZbidOpeningArrange/recordList',
        },
        exBiddingRoom: { list: '/exBiddingRoom/exBiddingRoom/list' },
      },
      roomList: [],
      dateList: [],
      dataSource: [
        // {
        //   key: '1',
        //   date: '2024-09-18',
        //   bs1: '1',
        //   bs2: '1',
        // },
        // {
        //   key: '2',
        //   date: '2024-09-17',
        //   bs1: '1',
        //   bs2: '0',
        // },
      ],

      columns: [
        {
          title: '日期',
          dataIndex: 'date',
          key: 'date',
        },
        // {
        //   title: '第一标室',
        //   dataIndex: 'bs1',
        //   key: 'bs1',
        // },
        // {
        //   title: '第一标室',
        //   dataIndex: 'bs2',
        //   key: 'bs2',
        // },
      ],
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    project: {},
    sectionList: {
      type: Array,
      default: () => {
        return []
      },
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  watch: {
    sectionList(newVal) {
      var that = this
      newVal.forEach((row) => {
        that.exSectionOptions.push({ label: row.bidSectionName + ' [ ' + row.bidSectionCode + ' ]', value: row.id })
      })
    },
    project(newVal){
      if(newVal){
        this.loadRoom()
      }
    }
  },
  created() {},
  methods: {
    addAfter() {
      return
      var that = this
      const now = moment().format('YYYY-MM-DD')
      for (let i = 1; i < 11; i++) {
        var dt = that.getNextDate(now, i)
        that.dateList.push(dt)
      }

      this.loadRoom()
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      var that = this
      const now = moment().format('YYYY-MM-DD')
      for (let i = 1; i < 11; i++) {
        var dt = that.getNextDate(now, i)
        that.dateList.push(dt)
      }

     // this.loadRoom()
    },
    next() {
      var that = this
      that.loadingMore = true
      var lastDate = that.dateList[that.dateList.length - 1]
      for (let i = 1; i < 11; i++) {
        var dt = that.getNextDate(lastDate, i)
        that.dateList.push(dt)
      }
      this.loadRoom()
    },
    validateError(msg) {
      this.$message.error(msg)
    },

    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    handleOk() {
      var that = this
      if (!that.model.exSectionIds || that.model.exSectionIds.split(',').length == 0) {
        that.$message.warning('请选择标段')
        return
      }
      if(!that.model.biddingRoomId){
        that.$message.warning('请选择标室')
        return
      }
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          var param = Object.assign({}, this.model)
          param.projectId = that.project.id
          param['exZbidChangdiandbdList'] = []
          for (let i = 0; i < that.model.exSectionIds.split(',').length; i++) {
            var item = { bidSectionId: that.model.exSectionIds.split(',')[i] }
            param['exZbidChangdiandbdList'].push(item)
          }
          param.status = 0
          httpAction(param.id ? this.url.edit : this.url.add, param, 'post')
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    getNextDate(date, day) {
      var dd = new Date(date)
      dd.setDate(dd.getDate() + day)
      var y = dd.getFullYear()
      var m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1
      var d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate()
      return y + '-' + m + '-' + d
    },
    loadRoom() {
      var that = this 
      that.confirmLoading = true
      getAction(this.url.exBiddingRoom.list,{sysPlatformCode:that.project.sysPlatformCode,pageSize:200})
        .then((res) => {
          if (res.success) {
            that.roomList = res.result.records
            that.columns = [
              {
                title: '时间',
                dataIndex: 'date',
                key: 'date',
              },
            ]
            that.dataSource = []
            // if (that.model.bidOpeningTime && !that.dateList.includes(that.model.bidOpeningTime)) {
            //   that.dateList = [that.model.bidOpeningTime, ...that.dateList]
            // }

            that.roomList.forEach((element) => {
              that.columns.push({
                title: element.roomName,
                dataIndex: element.roomCode,
                key: element.roomCode,
                scopedSlots: { customRender: 'action' },
              })
            })
            for (let i = 0; i < that.dateList.length; i++) {
              const date = that.dateList[i]
              var item = {
                key: i + 1,
                date: date,
              }
              that.roomList.forEach((room) => {
                item[room.roomCode] = i + 1 + '_' + room.id
              })
              that.dataSource.push(item)
            }

            that.loadRecordList()
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.confirmLoading = false
          that.loadingMore = false
        })
    },
    loadRecordList() {
      var that = this
      var param = {}
      getAction(this.url.records.list, param)
        .then((res) => {
          if (res.success) {
            //todo 加载已被选择的标室
            console.log(that.model)
            res.result.forEach((element) => {
              //element['bidOpeningTime']
              //element['bidding_room_id']
              var bidOpeningTime = moment(element['bidOpeningTime']).format('YYYY-MM-DD')
              var obj = that.dataSource.find((e) => e['date'] == bidOpeningTime)

              for (const key in obj) {
                if (Object.prototype.hasOwnProperty.call(obj, key)) {
                  if (key == 'date' || key == 'key') {
                    continue
                  }
                  const it = obj[key]
                  console.log(that.model)
                  if (
                    that.model.id == element.id &&
                    it.split('_')[1] === element['biddingRoomId'] &&
                    obj['date'] == bidOpeningTime
                  ) {
                    that.selectRoomItem = obj[key]
                    // 当前为需要选中的对象
                    continue
                  }
                  if (it.split('_')[1] === element['biddingRoomId']) {
                    obj[key] = it + '_' + 'true'
                  }
                }
              }
              // console.log('obj:', JSON.stringify(obj))
            })
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.confirmLoading = false
        })
    },
    changeSelectRoomItem(e) {
      this.model.biddingRoomId = e.target.value.split('_')[1]
    },
  },
}
</script>

<style scoped>
</style>
